/**
 * Created by Administrator on 2018/5/10.
 */
const express = require('express')
const Router = express.Router()
const utils = require('utility')
const models = require('./module')
const User = models.getModel('user')
const _filter = {'pwd':0,'__v':0}
Router.get('/list',function (req,res) {
  // User.remove({},function (e,d) {})
  const {type} = req.query
  User.find({type},function (err,doc) {
    return res.json({code:0,data:doc})
  })
})
Router.get('/info',function (req,res) {
  console.log( req.cookies)
  const {userid} = req.cookies
  if(!userid){
    return res.json({code:1})
  }
  User.findOne({'_id':userid} , _filter , function(err,doc){
    if(err){
      return res.json({code:1,msg:'后端出错了'})
    }
    if (doc){
      return res.json({code:0,data:doc})
    }else{
      return  res.json({code:1,msg:'没查出来?????？？？？？'})
    }
  })
})

Router.post('/regiest',function (req,res) {
  const {user, pwd,type} = req.body
  User.findOne({user},function(err,doc){
    if(doc){
      return res.json({code:1,msg:'用户名重复'})
    }
    const userModel = new User({user,pwd:md5Pwd(pwd),type})
    userModel.save(function(e,d){
      if(e){
        return res.json({code:1,msg:'后端出错了'})
      }
      const {user, type, _id} = d
      res.cookie('userid',_id)
      return res.json({code:0,data:{user,type,_id}})
    })

  })
})

Router.post('/login',function (req,res) {
  const {user, pwd} = req.body
  // {'pwd':0}返回的数据中，隐藏pwd
  User.findOne({user,pwd:md5Pwd(pwd)},_filter,function(err,doc){
    if(!doc){
      return res.json({code:1,msg:'用户名或者密码错误'})
    }else{
      res.cookie('userid',doc._id)
      return res.json({code:0,data:doc})
    }
  })
})

Router.post('/update',function(req,res){
  const userid = req.cookies.userid
  if(!userid){
    return res.json({code:1})
  }
  const body = req.body
  User.findByIdAndUpdate(userid,body,function(err,doc){
     if(err){
        return res.json({code:1,msg:'后端出错了'})
     }else{
        const data = Object.assign({},{
          user:doc.user,
          type:doc.type
        },body)

        return res.json({code:0,data:data})
     }
  })
})

function md5Pwd(pwd){
  let md5='abcdAbc123#'
  return utils.md5(utils.md5(pwd+md5))
}
module.exports = Router